import logging
from google.appengine.ext import db
from lib.Smurfy                  import Mechs as WebMechs
from lib.Toolbox                 import WebTools

class Mech(db.Model):
    name      = db.StringProperty(multiline=False)
    tonnage   = db.StringProperty(multiline=False)
    player    = db.StringProperty(multiline=False)
    speed     = db.IntegerProperty()
    dropid    = db.StringProperty(multiline=False)
    mechtype  = db.StringProperty(multiline=False)
    mechmodel = db.StringProperty(multiline=False)
    loadout   = db.StringProperty(multiline=False)
    lance     = db.StringProperty(multiline=False)
    starter   = db.IntegerProperty()
    position  = db.IntegerProperty()
    weapons   = db.ListProperty(str)
    modules   = db.ListProperty(str)
    firstStamp = db.DateTimeProperty( auto_now_add = True );
    lastStamp = db.DateTimeProperty( auto_now = True );
    
    def weight(self):
        mechs = WebMechs.list()
        
        if self.mechtype:
            return mechs[WebTools.utf8_ify(self.mechtype)]
        else:
            return 0

            
    def modules_as_string(self):
        return u", ".join( self.modules_as_list() )
    
    def modules_as_list(self):
        return (x for x in self.modules if x not in [u"ECM",u"BAP",u"Artemis",u"Jumpjets"])
    
    def equipment_as_string(self):
        return u", ".join( self.equipment_as_list() )
    
    def equipment_as_list(self):
        return (x for x in self.modules if x in [u"ECM",u"BAP",u"Artemis",u"Jumpjets"])
    
    def weapons_as_string(self):
        wa = [];
        wo = {};

        for w in self.weapons:
            if w in wo:
                wo[w] = wo[w] + 1;
            else:
                wa.append(w); 
                wo[w] = 1;                    
        
        ww = [];
        
        for w in wa:

            
            n = wo[w];
                     
            if n > 1:
                ww.append(str(n) + " " + w);
            else:
                ww.append(w);                    
        
        if len(ww) > 0:
            r = ""
            
            # for some reason ", ".join(ww) fails
            for wp in ww:
                r = wp + ", " + r
            
            r = r[:-2]
            
            return r
        else:
            return ""